package com.frx.fakeroutexposed;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.frx.fakeroutexposed.fragments.MapViewFragments;
import com.frx.fakeroutexposed.fragments.SettingsFragment;

public class MainActivity extends AppCompatActivity {

	private Intent service;
	private Toolbar toolbar;
	private ActionBarDrawerToggle mDrawerToggle;
	/** 侧滑导航菜单
	 * */
	private NavigationView mNavigationView;
	/** 侧滑导航布局
	* */
	private DrawerLayout mDrawerLayout;
	/** 主视图的 fragment
	 * */
	private MapViewFragments mMapFragment=null;
	/** 设置视图的 fragment
	 * */
	private SettingsFragment mSettingsFragment =null;
	/** 设置视图的 fragment 标签
	 * */
	private final String mFlag_SettingsFragment="settingsFragment";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//============================

		toolbar = (Toolbar) findViewById(R.id.custom_toolbar);
		//设置 Toolbar 为 ActionBar
		if (toolbar != null) {
			setSupportActionBar(toolbar);
			//设置返回键可用
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			getSupportActionBar().setHomeButtonEnabled(true);
			//getSupportActionBar().setDisplayShowHomeEnabled(true);
		}
		//============================
		//侧滑菜单
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
		// 侧滑导航抽屉的 打开/关闭 监听事件
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
				R.string.drawer_close){
			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);

				Log.d("DrawerLayout","关闭侧滑");
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);

				Log.d("DrawerLayout","打开侧滑");
			}
		};
		mDrawerLayout.addDrawerListener(mDrawerToggle);
		//============================
		//侧滑导航抽屉的点击选项监听
		mNavigationView=(NavigationView)findViewById(R.id.navigationView);
		mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
			@Override
			public boolean onNavigationItemSelected(@NonNull MenuItem item) {
				selectItem(item.getItemId());
				return true;
			}
		});


		//============================
		//设置默认的fragment
		if (savedInstanceState == null) {//防止从后台切换到前台,或者屏幕旋转时新建fragment
			mMapFragment = new MapViewFragments();
			getFragmentManager().beginTransaction()
					.replace(R.id.mainFrame, mMapFragment)
					.commit();
		}
		//============================


		// 获取记录轨迹的service
		service=((MyApp)this.getApplication()).getService();
		//这里启动service,
		startService(service);
	}
	/** 根据侧滑菜单选中项,切换主内容视力的 fragment */
	private void selectItem(int position){
		switch (position){
			case R.id.action_settings:
				//============================
				FragmentManager fm= getFragmentManager();
					//如果设置的 fragment 为空,则新建
				mSettingsFragment=(SettingsFragment) fm.findFragmentByTag(mFlag_SettingsFragment);
				if(null==mSettingsFragment){
					mSettingsFragment= new SettingsFragment();
				}
				if(mSettingsFragment.isAdded()){
					fm.beginTransaction()
							.hide(mMapFragment)
							.show(mSettingsFragment)
							.commit();
				}else{

					fm.beginTransaction()
							.hide(mMapFragment)
							.add(R.id.mainFrame, mSettingsFragment,mFlag_SettingsFragment)
							.addToBackStack(null)
							.commit();
				}

				//============================
				break;
			default:
				break;//TODO 本程序如果在后台运行,被系统 kill 后,界面重载问题,需要考虑
		}

		mNavigationView.setCheckedItem(position);
		mDrawerLayout.closeDrawers(); // 关闭导航菜单

	}
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Pass the event to ActionBarDrawerToggle, if it returns
		// true, then it has handled the app icon touch event
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle your other action bar items...

		return super.onOptionsItemSelected(item);
	}




	// 退出时间
	private long currentBackPressedTime = 0;

	// 退出间隔
	private static final int BACK_PRESSED_INTERVAL = 2000;
	@Override
	public void onBackPressed() {
		//如果 Fragment 的退回栈不回空,则弹出栈
		if(getFragmentManager().getBackStackEntryCount()>0){
			getFragmentManager().popBackStack();
			return;
		}

		// 判断时间间隔

		if (System.currentTimeMillis()- currentBackPressedTime > BACK_PRESSED_INTERVAL) {

			currentBackPressedTime = System.currentTimeMillis();

			Toast.makeText(this, getString(R.string.toast_back_key), Toast.LENGTH_SHORT).show();

		} else {
			// 退出
			stopService(service);
            // 结束当前Activity，不会立即释放内存。遵循android内存管理机制。
            finish();
            // exit() 方法不会调用 Activity 的生命周期方法
			//System.exit(0);
		}
	}
}
